from rest_framework.views import APIView
from rest_framework.response import Response
from api.serializer.account import LoginSerializer
from api import models
# from utils.tencent.msg import send_message
from utils.ronglian.sms import send_message
import uuid


class LoginView(APIView):
    def post(self, request, *args, **kwargs):
        ser = LoginSerializer(data=request.data)

        if not ser.is_valid():
            print(ser.errors)
            return Response({'status': False, 'message': ser.errors.get('code')[0]})
        phone = ser.validated_data.get('phone')
        nickname = ser.validated_data.get('nickname')
        avatar = ser.validated_data.get('avatar')
        # 获取openid(需要拿着wx_code去申请)
        wx_code = ser.validated_data.get('wx_code')

        # info = {
        #     'appid': "wxe459ac5ae8f95261",
        #     'secret': "363c2392a215f7591ef8d6f3e616c173",
        #     'js_code': wx_code,
        #     'grant_type': "authorization_code"
        # }
        # result = requests.get(url="https://api.weixin.qq.com/sns/jscode2session", params=info)
        # print(result.json())
        print(avatar)
        user_object, flag = models.UserInfo.objects.get_or_create(phone=phone, nickname=nickname, avatar=avatar)
        print(user_object, flag)
        user_object.token = str(uuid.uuid4())
        user_object.save()
        return Response({'status': True, 'data': {"token": user_object.token, "phone": phone}})
